package com.huihe.framework.service;

import cn.hutool.core.util.StrUtil;
import com.huihe.common.constant.UserConstants;
import com.huihe.common.utils.SecurityUtils;
import com.huihe.storage.dto.RegisterBody;
import com.huihe.storage.entity.SysUser;
import com.huihe.storage.entity.SysUserRole;
import com.huihe.storage.repository.SysUserRepository;
import com.huihe.storage.repository.SysUserRoleRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@AllArgsConstructor
public class RegisterService {

    /**
     * 用户的 Repository 层
     */
    SysUserRepository sysUserRepository;

    /**
     * 用户关联角色的 Repository 层
     */
    SysUserRoleRepository sysUserRoleRepository;

    /**
     * 注册
     */
    public String register(RegisterBody registerBody)
    {
        String msg = "";
        String account = registerBody.getUsername();
        String password = registerBody.getPassword();

        SysUser sysUser = new SysUser();
        sysUser.setAccount(account);

        if (StrUtil.isEmpty(account)) {
            msg = "用户名不能为空";
        } else if (StrUtil.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (account.length() < UserConstants.USERNAME_MIN_LENGTH
                || account.length() > UserConstants.USERNAME_MAX_LENGTH) {
            msg = "账户长度必须在" + UserConstants.USERNAME_MIN_LENGTH + "到" + UserConstants.USERNAME_MAX_LENGTH + "个字符之间";
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在" + UserConstants.PASSWORD_MIN_LENGTH + "到" + UserConstants.PASSWORD_MAX_LENGTH + "个字符之间";
        } else if (!sysUserRepository.checkUserNameUnique(account)) {
            msg = "保存用户失败，注册账号已存在";
        } else {
            //密码加密
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            boolean regFlag = sysUserRepository.registerUser(sysUser);
            if (!regFlag) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                //注册功能的用户,统统是游客,保存这个用户和角色的关联关系.
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(sysUser.getId());
                sysUserRole.setRoleId("409b7224-0799-11f0-9119-00ff266d2067");
                sysUserRoleRepository.save(sysUserRole);
                //记录到日志系统
                log.info("注册成功");
            }
        }
        return msg;
    }
}
